<template>
  <div class="drug-list">
    <!-- 搜索和筛选 -->
    <div class="filter-bar">
      <select v-model="selectedCategory" @change="filterDrugs">
        <option value="">全部分类</option>
        <option value="prescription">处方药</option>
        <option value="otc">非处方药</option>
        <option value="supplement">保健品</option>
        <option value="chinese">中成药</option>
      </select>
      
      <input 
        v-model="searchQuery"
        type="text" 
        placeholder="药品名称/拼音码/条码" 
        @input="searchDrugs"
      >
      
      <button @click="searchDrugs">查询</button>
      <button @click="resetSearch">重置</button>
      
      <div class="total-count">
        总计: <strong>{{ filteredDrugs.length }}</strong> 种药品
      </div>
    </div>

    <!-- 药品表格 -->
    <table class="data-table">
      <thead>
        <tr>
          <th width="30">
            <input 
              type="checkbox" 
              v-model="selectAll"
              @change="handleSelectAll"
            >
          </th>
          <th width="80">药品编码</th>
          <th width="150">药品名称</th>
          <th width="100">规格</th>
          <th width="80">生产厂家</th>
          <th width="60">库存</th>
          <th width="60">单价</th>
          <th width="80">有效期</th>
          <th width="100">操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="drug in paginatedDrugs" :key="drug.id">
          <td>
            <input 
              type="checkbox" 
              v-model="selectedDrugs"
              :value="drug.id"
            >
          </td>
          <td>{{ drug.code }}</td>
          <td>
            {{ drug.name }}
            <span 
              class="drug-type" 
              :class="drug.type"
            >
              {{ drug.typeLabel }}
            </span>
          </td>
          <td>{{ drug.specification }}</td>
          <td>{{ drug.manufacturer }}</td>
          <td :style="{ color: drug.stock < drug.safeStock ? '#e74c3c' : '#333' }">
            {{ drug.stock }}
          </td>
          <td>¥{{ drug.price.toFixed(2) }}</td>
          <td>{{ drug.expiryDate }}</td>
          <td>
            <button class="action-btn" @click="editDrug(drug.id)">编辑</button>
            <button class="action-btn" @click="viewStock(drug.id)">库存</button>
            <button class="action-btn danger" @click="deleteDrug(drug.id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 分页器 -->
    <div class="pagination">
      <div>显示第 {{ startIndex }}-{{ endIndex }} 条，共 {{ filteredDrugs.length }} 条记录</div>
      <div class="pagination-controls">
        <button @click="goToPage(1)" :disabled="currentPage === 1">首页</button>
        <button @click="goToPage(currentPage - 1)" :disabled="currentPage === 1">上一页</button>
        
        <button 
          v-for="page in visiblePages" 
          :key="page"
          @click="goToPage(page)"
          :class="{ active: page === currentPage }"
        >
          {{ page }}
        </button>
        
        <button @click="goToPage(currentPage + 1)" :disabled="currentPage === totalPages">下一页</button>
        <button @click="goToPage(totalPages)" :disabled="currentPage === totalPages">末页</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

// 定义数据类型
interface Drug {
  id: string
  code: string
  name: string
  specification: string
  manufacturer: string
  stock: number
  safeStock: number
  price: number
  expiryDate: string
  type: 'prescription' | 'otc' | 'supplement' | 'chinese'
  typeLabel: string
}

// 响应式数据
const searchQuery = ref('')
const selectedCategory = ref('')
const selectedDrugs = ref<string[]>([])
const selectAll = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)

// 模拟药品数据
const drugs = ref<Drug[]>([
  {
    id: 'D001',
    code: 'D001',
    name: '阿莫西林胶囊',
    specification: '0.25g×24粒',
    manufacturer: '华北制药',
    stock: 15,
    safeStock: 50,
    price: 18.50,
    expiryDate: '2025-06-15',
    type: 'prescription',
    typeLabel: '处方'
  },
  {
    id: 'D002',
    code: 'D002',
    name: '布洛芬片',
    specification: '0.3g×20片',
    manufacturer: '中美史克',
    stock: 120,
    safeStock: 40,
    price: 15.60,
    expiryDate: '2025-08-22',
    type: 'otc',
    typeLabel: 'OTC'
  },
  {
    id: 'D003',
    code: 'D003',
    name: '维生素B复合片',
    specification: '100片/瓶',
    manufacturer: '汤臣倍健',
    stock: 8,
    safeStock: 30,
    price: 45.00,
    expiryDate: '2025-03-20',
    type: 'supplement',
    typeLabel: '保健品'
  },
  {
    id: 'D004',
    code: 'D004',
    name: '感冒灵颗粒',
    specification: '10g×9袋',
    manufacturer: '999医药',
    stock: 45,
    safeStock: 30,
    price: 12.80,
    expiryDate: '2024-02-01',
    type: 'otc',
    typeLabel: 'OTC'
  },
  {
    id: 'D005',
    code: 'D005',
    name: '板蓝根颗粒',
    specification: '10g×12袋',
    manufacturer: '白云山',
    stock: 68,
    safeStock: 40,
    price: 9.80,
    expiryDate: '2025-07-15',
    type: 'chinese',
    typeLabel: '中成药'
  }
])

// 计算属性
const filteredDrugs = computed(() => {
  let result = drugs.value

  // 按分类筛选
  if (selectedCategory.value) {
    result = result.filter(drug => drug.type === selectedCategory.value)
  }

  // 按搜索关键词筛选
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(drug => 
      drug.name.toLowerCase().includes(query) ||
      drug.code.toLowerCase().includes(query) ||
      drug.manufacturer.toLowerCase().includes(query)
    )
  }

  return result
})

const totalPages = computed(() => {
  return Math.ceil(filteredDrugs.value.length / pageSize.value)
})

const startIndex = computed(() => {
  return (currentPage.value - 1) * pageSize.value + 1
})

const endIndex = computed(() => {
  const end = currentPage.value * pageSize.value
  return Math.min(end, filteredDrugs.value.length)
})

const paginatedDrugs = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredDrugs.value.slice(start, end)
})

const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

// 方法
const searchDrugs = () => {
  currentPage.value = 1
  // 搜索逻辑已在computed中处理
}

const resetSearch = () => {
  searchQuery.value = ''
  selectedCategory.value = ''
  currentPage.value = 1
}

const filterDrugs = () => {
  currentPage.value = 1
  // 筛选逻辑已在computed中处理
}

const handleSelectAll = () => {
  if (selectAll.value) {
    selectedDrugs.value = paginatedDrugs.value.map(drug => drug.id)
  } else {
    selectedDrugs.value = []
  }
}

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

const editDrug = (drugId: string) => {
  alert(`编辑药品: ${drugId}`)
}

const viewStock = (drugId: string) => {
  alert(`查看库存: ${drugId}`)
}

const deleteDrug = (drugId: string) => {
  if (confirm('确定要删除这个药品吗？')) {
    const index = drugs.value.findIndex(drug => drug.id === drugId)
    if (index !== -1) {
      drugs.value.splice(index, 1)
      alert(`已删除药品: ${drugId}`)
    }
  }
}

// 监听选中状态变化
const updateSelectAll = () => {
  selectAll.value = selectedDrugs.value.length === paginatedDrugs.value.length && paginatedDrugs.value.length > 0
}

onMounted(() => {
  // 初始化时监听选中状态
  updateSelectAll()
})
</script>

<style scoped>
.drug-list {
  font-size: 12px;
}

/* 筛选栏 */
.filter-bar {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  background: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.filter-bar select {
  width: 120px;
  height: 28px;
  border: 1px solid #ddd;
  border-radius: 3px;
  padding: 0 8px;
  font-size: 12px;
}

.filter-bar input {
  width: 200px;
  height: 26px;
  border: 1px solid #ddd;
  border-radius: 3px;
  padding: 0 8px;
  font-size: 12px;
}

.filter-bar button {
  background: white;
  border: 1px solid #ddd;
  padding: 5px 12px;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
  height: 28px;
}

.filter-bar button:hover {
  background: #e8f4f8;
  border-color: #3498db;
}

.total-count {
  margin-left: auto;
  font-size: 12px;
  color: #666;
}

/* 表格样式 */
.data-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #ddd;
  font-size: 12px;
  margin-bottom: 15px;
}

.data-table th {
  background: #f8f9fa;
  border: 1px solid #ddd;
  padding: 6px 8px;
  text-align: left;
  font-weight: bold;
  font-size: 11px;
  color: #666;
}

.data-table td {
  border: 1px solid #ddd;
  padding: 4px 8px;
  vertical-align: top;
}

.data-table tr:nth-child(even) {
  background: #f9f9f9;
}

.data-table tr:hover {
  background: #e8f4f8;
}

/* 药品类型标签 */
.drug-type {
  font-size: 10px;
  padding: 1px 4px;
  border-radius: 2px;
  font-weight: bold;
  margin-left: 5px;
}

.drug-type.prescription {
  background: #ffebee;
  color: #c62828;
  border: 1px solid #ffcdd2;
}

.drug-type.otc {
  background: #e8f5e8;
  color: #2e7d32;
  border: 1px solid #c8e6c9;
}

.drug-type.supplement {
  background: #e3f2fd;
  color: #1976d2;
  border: 1px solid #bbdefb;
}

.drug-type.chinese {
  background: #fff3e0;
  color: #ef6c00;
  border: 1px solid #ffcc02;
}

/* 操作按钮 */
.action-btn {
  background: none;
  border: none;
  color: #3498db;
  cursor: pointer;
  text-decoration: underline;
  font-size: 11px;
  padding: 2px 4px;
  margin-right: 5px;
}

.action-btn:hover {
  color: #2980b9;
}

.action-btn.danger {
  color: #e74c3c;
}

.action-btn.danger:hover {
  color: #c0392b;
}

/* 分页器 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 11px;
  color: #666;
}

.pagination-controls {
  display: flex;
  gap: 2px;
}

.pagination-controls button {
  background: white;
  border: 1px solid #ddd;
  padding: 4px 8px;
  cursor: pointer;
  font-size: 11px;
  border-radius: 3px;
}

.pagination-controls button:hover:not(:disabled) {
  background: #e8f4f8;
}

.pagination-controls button.active {
  background: #3498db;
  color: white;
  border-color: #3498db;
}

.pagination-controls button:disabled {
  background: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
}

/* 响应式 */
@media (max-width: 768px) {
  .filter-bar {
    flex-wrap: wrap;
  }
  
  .filter-bar input {
    width: 150px;
  }
  
  .total-count {
    margin-left: 0;
    width: 100%;
    margin-top: 5px;
  }
}
</style> 